package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author DCSGO
 * @version 1.0
 * 服务端
 * 使用字符流接收客户端发送的消息
 * 并向客户端回传"你好，客户端！"
 */
public class SocketTCP03Server {
    public static void main(String[] args) throws IOException {
        int port = 9999;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("正在监听 " + port + " 端口...");
        Socket socket = serverSocket.accept();
        System.out.println("有主机连接到 " + port + " 端口！");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        System.out.println("正在读取主机发送的消息...");
        while ((line = bufferedReader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println("主机发送的消息已接收!");
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        System.out.println("正在向主机发送回传消息...");
        bufferedWriter.write("你好，客户端！");
        //字符流的读取常用 readLine 为与之对应 故加上 newLine 防止出现 Bug
        bufferedWriter.newLine();
        bufferedWriter.flush();//必须刷新才能真正写入字符
        socket.shutdownOutput();//设置写入结束标记

        bufferedWriter.close();
        bufferedReader.close();
        socket.close();
        serverSocket.close();
        System.out.println("程序已结束...");

        /*
         * 正在监听 9999 端口...
         * 有主机连接到 9999 端口！
         * 正在读取主机发送的消息...
         * 你好，服务端！
         * 主机发送的消息已接收!
         * 正在向主机发送回传消息...
         * 程序已结束...
         *
         * 进程已结束，退出代码为 0
         */
    }
}
